package com.client.controller;

import com.client.pojo.BrowseHistory;
import com.client.service.BrowseHistoryService;
import com.client.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.Date;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户浏览历史表 前端控制器
 * </p>
 *
 * @author ckick
 * @since 2025-09-20 08:28:54
 */
@RestController
@RequestMapping("/browseHistory")
public class BrowseHistoryController {
    @Autowired
    private BrowseHistoryService browseHistoryService;

    /**
     * 获取用户浏览词条浏览记录
     * @param userID 用户ID
     * @return 浏览记录
     */
    @GetMapping("getHistory/{userID}")
    public ResponseMsg getHistory(@PathVariable Integer userID) {
        List<BrowseHistory> list = browseHistoryService.getByIds(userID);
        if (list == null) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR,"暂无浏览历史~");
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"查询浏览历史~",list);
    }



    /**
     * 新增用户浏览记录，增加之前先查有没有，有则更新，没有则新增，保证每个用户每个词条只存在一条记录
     * @param browseHistory 浏览记录
     * @return 新增结果
     */
    @PostMapping("addHistory")
    public String addHistory(@RequestBody Map<String,Object> param) {
        Integer userId = (Integer) param.get("userId");
        Integer entryId = (Integer) param.get("entryId");
        
        BrowseHistory browseHistory = new BrowseHistory();
        browseHistory.setUserId(userId);
        browseHistory.setEntryId(entryId);
        // 先查询是否存在相同的记录
        BrowseHistory existingHistory = browseHistoryService.getOne(new QueryWrapper<BrowseHistory>()
                .eq("user_id", userId)
                .eq("entry_id", entryId));
        if (existingHistory != null) {
            // 如果存在，更新时间
            existingHistory.setBrowseTime(new Date());
            return browseHistoryService.updateById(existingHistory) ? "更新成功" : "更新失败";
        }
        // 如果不存在，新增记录
        boolean isSuccess = browseHistoryService.save(browseHistory);
        if (isSuccess) {
            return "增加成功";
        }
        return "增加失败"; 
   }
}
